package http_proxy_middleware

import (
	"fmt"

	"gin-gateway/middleware"
	"gin-gateway/core/utils"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
)

// HTTPJwtFlowCountMiddleware jwt 流量统计、租户流量限流
func HTTPJwtFlowCountMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		appInfo := GetApp(c)

		appCounter, err := utils.FlowCountManager.GetRedisCounter(utils.FlowAppPrefix + appInfo.AppID)
		if err != nil {
			middleware.ResponseError(c, 2002, err)
			c.Abort()
			return
		}
		appCounter.Increase()

		if appCounter.TotalCount > appInfo.Qpd && appInfo.Qpd > 0 { // 租户流量限流
			middleware.ResponseError(c, 2003, errors.New(fmt.Sprintf("租户日请求量限流 limit:%v current:%v", appInfo.Qpd, appCounter.TotalCount)))
			c.Abort()
			return
		}
		c.Next()
	}
}
